import React, { useEffect, useRef } from "react";
import mermaid from 'mermaid';
import * as echarts from 'echarts';

// 自定义组件 - 流程图渲染器
const MermaidRenderer = ({ chartCode }: { chartCode: string }) => {
    const containerRef = useRef(null);

    useEffect(() => {
        if (containerRef.current && chartCode) {
            // 清除容器内容
            containerRef.current.innerHTML = '';

            // 生成唯一的ID
            const id = 'mermaid-' + Math.random().toString(36).slice(2, 9);

            // 创建临时元素用于mermaid渲染
            const tempDiv = document.createElement('div');
            tempDiv.className = 'mermaid';
            tempDiv.id = id;
            tempDiv.textContent = chartCode;

            // 添加到容器
            containerRef.current.appendChild(tempDiv);

            // 初始化并渲染mermaid
            mermaid.initialize({
                startOnLoad: true,
                theme: 'forest',
                flowchart: {
                    useMaxWidth: true,
                    htmlLabels: true
                }
            });

            // 渲染图表
            mermaid.run({
                nodes: [tempDiv],
            });
        }
    }, [chartCode]);

    return (
        <div className="flowchart-container">
            <div ref={containerRef} />
        </div>
    );
};

// 自定义组件 - ECharts 渲染器
const EChartsRenderer = ({ chartConfig }: { chartConfig: string }) => {
    const chartRef = useRef(null);
    const chartInstance = useRef(null);

    useEffect(() => {
        if (chartRef.current) {
            // 初始化图表实例
            chartInstance.current = echarts.init(chartRef.current);

            // 窗口大小变化时重绘图表
            const handleResize = () => {
                chartInstance.current?.resize();
            };

            window.addEventListener('resize', handleResize);

            return () => {
                window.removeEventListener('resize', handleResize);
                chartInstance.current?.dispose();
            };
        }
    }, []);

    useEffect(() => {
        if (chartInstance.current && chartConfig) {
            try {
                // 解析并设置图表配置
                const option = typeof chartConfig === 'string'
                    ? JSON.parse(chartConfig)
                    : chartConfig;

                chartInstance.current.setOption(option);
            } catch (error) {
                console.error('ECharts配置解析错误:', error);
                chartRef.current.innerHTML = `<div style="color:red; padding:20px; text-align:center;">
            ECharts配置错误: ${error.message}
          </div>`;
            }
        }
    }, [chartConfig]);

    return (
        <div className="chart-container">
            <div ref={chartRef} style={{ width: '100%', height: '400px' }} />
        </div>
    );
};


export const CustomCode = ({ inline, className, children, ...props }) => {
    const match = /language-(\w+)/.exec(className || '');
    const language = match ? match[1] : '';
    const code = String(children).replace(/\n$/, '');

    // 处理流程图
    if (language === 'mermaid') {
        return <MermaidRenderer chartCode={code} />;
    }

    // 处理ECharts图表
    if (language === 'echarts') {
        return <EChartsRenderer chartConfig={code} />;
    }

    // 默认代码块渲染
    if (!inline && match) {
        return (
            <pre className={className}>
                <code {...props}>{children}</code>
            </pre>
        );
    }

    // 内联代码
    return <code className={className} {...props}>{children}</code>;
};